/**
 *
 */
package org.whuims.pois.action;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.whuims.pois.dao.LoginDao;
import org.whuims.pois.hibernate.BaseDao;
import org.whuims.pois.model.DataC;
import org.whuims.pois.model.TopicC;
import org.whuims.pois.model.User;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

public class LoginAction extends Action {


    public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {
        BaseDao baseDao = new BaseDao();
        String user = request.getParameter("user");
        String password = request.getParameter("password");
        if (user.equals("") || password.equals("")) {
            request.setAttribute("errormessage", "请输入用户名和密码！");
            return mapping.findForward("error");
        }

        LoginDao dao = new LoginDao();
        boolean flag = dao.validate(user, password);
        if (flag) {
            HttpSession session = request.getSession();
            session.setAttribute("user", "administrator");  //用户角色
            //设置当前用户和主题
            session.setAttribute("userName", user); //用户名
            List<User> list = baseDao.findByParamsArr("from User where user= ?", user);
            long topicId = list.get(0).getTopicid();
            int privilege = list.get(0).getLevel();
            //主题语种数
            int languagecount = baseDao.query("select distinct planguage from DataC where topicid='"+topicId+"'").size();
            session.setAttribute("languagecount", languagecount);
            session.setAttribute("topicId", topicId);   //设置topicId
            session.setAttribute("privilege", privilege); //设置用户权限
            TopicC topicC = (TopicC) baseDao.getByPk(TopicC.class, topicId);
            if (topicC != null) {
                session.setAttribute("topicName", topicC.getName());//当前主题名称
            }

          return mapping.findForward("success");
        } else
            request.setAttribute("errormessage", "用户名或密码错误！");
        return mapping.findForward("error");

    }

}
